//消费者(read)
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
#define MAX 100

void *pAddr;
int shmId;

struct Msg {
  int flag;
  char content[MAX];
};

int main() {
  int i = 0;
  key_t key = ftok(".", 2);
  shmId = shmget(key, 0, 0); // key与writed的key相同，后两个0表示获取该共享内存

  pAddr = shmat(shmId, 0, 0); //获取共享内存的地址

  if (*(int *)pAddr == -1) {
    printf("shmat error!\n");
    exit(0);
  }

  struct Msg *msg = (struct Msg *)pAddr;
  while (1) {
    if (msg->flag == 0) { //当为0时读消息,此时写文件中不能操作此共享内存
      printf("%s\n", msg->content);
      msg->flag = 1;
    } else {
      sleep(1);
    }
  }

  return 0;
}